import json
import queue
import serial
import threading
import socket
from time import sleep

class Net_UDP(object):
	def __init__(self, ip_addr, port):
		self.callbackList = {}
		self.recvQue = queue.Queue(10)
		self.sendQue = queue.Queue(1)

		# 建立socket连接
		self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		# 绑定地址和端口
		self.sock.bind((ip_addr, port))

		def recvDaemon():
			while True:
				try:
					msg = self.sock.recvfrom(1024)
					if self.recvQue.full():
						self.recvQue.get()
					self.recvQue.put(msg[0])
					
					print("[module -> pc]: recv ", msg)
				except Exception as e:
					print("error!!!!!!")
					print(e)

		threading.Thread(target = recvDaemon,daemon=True).start()

	def flush(self):
		if self.recvQue.full():
			self.recvQue.get()
			
	def is_queue_recv_empty(self):
		return self.recvQue.empty()
	
	def get_queue_recv(self):
		return self.recvQue.get()

	# 发送数据给目标UDP， ('192.168.0.111', 8089)
	def send_data_to_device(self, data):
		da = [0x01, 0x02, 0x04, 0x05, 0xff]
		# self.sock.sendto(data.encode('utf-8'),  ('192.168.0.111', 8089))
		self.sock.sendto(bytearray(da),  ('192.168.0.111', 8089))

	def get_data_from_device(self):
		if (not self.is_queue_recv_empty()):
			data = self.get_queue_recv()
			# AA BB 01 32 FF，直接去data[3]有效数据， AA BB为帧头， 
			if (0xAA == data[0] and 0xBB == data[1] and 0xFF == data[4]):
				return data[3], data
			else:
				return None, None
		else:
			return None, None

# udp = Net_UDP("192.168.0.111", 8989)

# UDP接收数据
# while True:
# 	if (not udp.is_queue_recv_empty()):
# 		data = udp.get_queue_recv()
# 		lens = list(data)
# 		print("recv data is ", lens)
# 		for it in lens:
# 			print(it)
# 		print("recv data's len : ", len(lens))

# UDP发送数据
# while True:
# 		# 1. 输入数据
# 		data = input("Please input data:\r\n")
# 		if data == "exit":
# 			break
# 		udp.send_data_to_device(data)

